let ID = location.search.split("=")[1];
//发送ajax
ajax({
	method: "get",
	dataType: "json",
	url: "./product.php",
	data: {
		ID
	}
}).then(res => {
	// console.log(res);
	//渲染视图
	renderDom(res);
	// 存在本地数据
	localStorage.setItem("pid", ID);
	localStorage.setItem("num", 1);
})

let centerEle = document.querySelector(".center");

function renderDom(data) {
	centerEle.innerHTML = "";
	data.forEach(item => {
		centerEle.innerHTML = `
					<div class="box">
						<div class="show">
							<img src="${item.goodsimg}" alt="">
							<div class="mask"></div>
						</div>
					 <div class="enlarge" style="width: 400px;height: 400px;position: absolute;top: 0;left: 101%;background:url(${item.goodsimg});background-size: 800px 800px;background-position:0 0"></div>
					</div>
					<div class="boxx">
						<h2>${item.goodstype}</h2>
						<p>价格
							<span id="sp">￥${item.goodsprice}</span>
						</p>
						<p>由 京东 发货, 读书郎京东自营旗舰店提供售后服务. 23:00前下单，预计明天送达</p>
						<div class="boxxx">
							数量：<input type="" name="" id="buy_num" value="1" />
							<div class="addbox">
								<a id="add_goods" style="cursor:pointer">+</a>
								<a id="min_goods" style="cursor:pointer">-</a>
							</div>
						</div>
						<a class="shoppingcar" style="cursor:pointer" onclick="checkCartUser()"> 加入购物车 </a>
						<p>温馨提示：支持七天无理由退换货</p>
					</div>
		`
		fdj();
		updataGoods();
	})

}

//获取localStorage
function checkCartUser() {
	let user = localStorage.getItem("username");
	if (user == null || user == "") {
		alert("请登录账号后再购买或加入购物车！")
		window.location.href = "./register.html";
	} else {
		localStorage.setItem("pid", ID);
		carts();
		// window.location.href = "./cart.html";
		alert("添加成功");
	}
}
// //点击退出销毁缓存
function exit() {
	localStorage.clear();
	checkCartUser();
}
// 修改数量
function updataGoods() {
	let numEle = document.querySelector("#buy_num");
	let addEle = document.querySelector("#add_goods");
	let minEle = document.querySelector("#min_goods");
	addEle.onclick = function() {
		numEle.value++;
		localStorage.setItem("num", numEle.value);
	}
	minEle.onclick = function() {
		if (numEle.value < "1" || numEle.value == "1") {
			alert("商品数量最少为1");
			localStorage.setItem("num", 1);
			}else {
				numEle.value--;
				localStorage.setItem("num", numEle.value);
			}
		}
	}

 //存购物车表
    function carts(){
        let user = localStorage.getItem("username");
        let goodsNum = localStorage.getItem("num");
        ajax({
            url:"./shoppingCart.php",
            data:{
                uid:user,
                pid:ID,
                num:goodsNum
            }
        }).then(res=>{
            console.log(res);
        })
    }